package team.first.movieapiv2.controller;

import cn.hutool.core.bean.BeanUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import dev.morphia.Datastore;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import team.first.movieapiv2.doc.CommentDoc;
import team.first.movieapiv2.doc.UserDoc;
import team.first.movieapiv2.domain.User;
import team.first.movieapiv2.util.MongoDBUtil;
import team.first.movieapiv2.vo.ApiResponse;

import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2.controller
 * @Date: 2021/12/9 15:05
 * @Description:
 */
@RestController
public class UserController {
    /**
     * 2.1 POST 用户注册接口
     * @param user 要注册的用户的部分信息
     * @return 返回注册后的用户的全部信息，也就只是多个个自增id
     */
    @PostMapping("/api/v2/register")
    @ApiOperation("2.1 POST 用户注册接口")
    public ApiResponse<User> register(@ApiParam("要注册的用户信息") User user) {
        ApiResponse<User> apiResponse = new ApiResponse<>();
        Datastore datastore = MongoDBUtil.getDataStore();
        datastore.getMapper().mapPackage("team.first.movieapiv2.doc");
        UserDoc userDoc = new UserDoc();
        BeanUtil.copyProperties(user, userDoc);
        try{
            datastore.save(userDoc);
            apiResponse.setCode(200).setSuccess(true).setMessage("注册成功").setData(user);
        } catch (Exception e){
            e.printStackTrace();
            apiResponse.setCode(500).setSuccess(false).setMessage("注册失败").setData(user);
        }
        return apiResponse;
    }

    /**
     * 2.2 POST 用户登录接口
     * @param user 登录的用户部分信息
     * @return 返回登录后的用户全部信息
     */
    @PostMapping("/api/v2/login")
    @ApiOperation("2.2 POST 用户登录接口")
    public ApiResponse<User> login(User user) {
        ApiResponse<User> apiResponse = new ApiResponse<>();
        DBCollection collection = MongoDBUtil.getCollection("user");

        // 查询用户信息
        // 建立查询条件
        BasicDBObject filter_dbobject = new BasicDBObject();
        filter_dbobject.put("email", user.getEmail());
        filter_dbobject.put("password", user.getPassword());

        // 条件查询
        DBCursor cursor = collection.find(filter_dbobject).sort(new BasicDBObject("id", 1));

        // 将结果转为集合
        List<DBObject> dbObjectList = cursor.toArray();
        // 属性拷贝
        List<User> userList = BeanUtil.copyToList(dbObjectList, User.class);
        if (userList.size() > 0) {
            apiResponse.setCode(200).setSuccess(true).setMessage("登录成功").setData(userList.get(0));
        }else{
            apiResponse.setCode(500).setSuccess(false).setMessage("登录失败");
        }
        return apiResponse;
    }
}
